package org.wlci.captur.service;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.New;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;

@ApplicationScoped
public class TestService implements TestServiceLocal, TestServiceRemote {

	@Produces
	@TestApplicationInterfaceQualifier
	public TestApplicationInterface createTestApplicationInterface(@New TestApplicationInterfaceImpl impl) {
		System.out.println( "Produce Test SERVICE result!!!" );
		return impl;
	}

	public TestApplicationInterface createTestApplicationInterface2() {
		return getApplicationInterface( TestApplicationInterface.class ); 
	}
	
	private <T> T getApplicationInterface( Class<T> type ) {
		
        BeanManager bm = getBeanManager();
        
        Bean<T> bean = (Bean<T>) bm.getBeans(type).iterator().next();

        return (T) bm.getReference(bean, type, bm.createCreationalContext(bean) );
        
	}
	
	public BeanManager getBeanManager() {
        try {
            InitialContext initialContext = new InitialContext();
            return (BeanManager) initialContext.lookup("java:comp/BeanManager");
        } catch (NamingException e) {
            return null;
        }
    }
	
}
